#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/23 11:07
import os
from public_tools.common_vars import  log
import paramiko


class LinuxClient:
    def __init__(self, host: str, port: int = 22, user: str = "root", pwd: str = None, private_key_file: str = None):
        # 进行SSH连接
        self.trans = paramiko.Transport((host, port))
        self.host = host
        if pwd is None:
            self.trans.connect(username="root", pkey=paramiko.RSAKey.from_private_key_file(private_key_file))
        else:
            self.trans.connect(username=user, password=pwd)
        # 将sshclient的对象的transport指定为以上的trans
        self.ssh = paramiko.SSHClient()
        self.ssh._transport = self.trans
        # 创建SFTP客户端
        self.ftp_client = paramiko.SFTPClient.from_transport(self.trans)

    def execute_cmd(self, cmd: str):
        """
        :param cmd: 服务器下对应的命令, 可以是list，或者str
        """
        try:
            if isinstance(cmd, list):
                for c in cmd:
                    stdin, stdout, stderr = self.ssh.exec_command(c)
                    log.info(f"【execute cmd】{stdout.read().decode()}")
                    return stdout.read().decode()
            else:
                stdin, stdout, stderr = self.ssh.exec_command(cmd)
                log.info(f"【execute cmd】{stdout.read().decode()}")
                return stdout.read().decode()
        except Exception as e:
            log.error(f"【execute cmd exception is】{e}")

    def files_action(self, post: bool, local_path: str = os.getcwd(), remote_path: str = "/root"):
        """
        :param post: 动作 为 True 就是上传， False就是下载
        :param local_path: 本地的文件路径， 默认当前脚本所在的工作目录
        :param remote_path: 服务器上的文件路径，默认在/root目录下
        """
        if post:  # 上传文件
            if remote_path[-1] != "/":
                remote_path += "/"
            self.ftp_client.put(localpath=local_path, remotepath=f"{remote_path}{os.path.split(local_path)[1]}")
            log.info(f"【文件上传成功】 {local_path} -> {self.host}:{remote_path}{os.path.split(local_path)[1]}")
        else:  # 下载文件
            if local_path[-1] != "\\":
                local_path += "\\"
            self.ftp_client.get(ocalpath=f"{local_path}{os.path.split(remote_path)[1]}", remotepath=remote_path)
            log.info(f"【文件下载成功】 {self.host}:{remote_path}{os.path.split(local_path)[1]} -> {local_path}")

    def ssh_close(self):
        """关闭连接"""
        self.trans.close()
        log.warning("已关闭SSH连接...")
